<template>
  <div class="app-container">
    <div class="collect-equipment-status">
      <div class="status-card-wrapper">
        <div class="status-card" v-for="card in statusCardList" :key="card.label">
          <span class="status-label">{{ card.label }}</span>
          <span class="status-value" :class="card.type">
            {{ equipmentStatus[card.key] || 0 }}
          </span>
        </div>
      </div>

      <el-form :inline="true" :model="queryForm" class="filter-form">
        <el-form-item label="所属商户" class="form-item-wrapper">
          <el-select
            v-model="queryForm.tenantId"
            placeholder="请输入所属商户"
            filterable
            remote
            clearable
            :remote-method="searchMerchant"
            style="width: 180px"
            @change="handleMerchantChange"
          >
            <el-option
              v-for="item in merchantList"
              :key="item.id"
              :label="item.tenantName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
                <el-form-item label="所在地点位置" class="form-item-wrapper">
          <el-tree-select
            v-model="queryForm.locationIds"
            :data="fullLocationTree"
            :props="locationTreeProps"
            node-key="id"
            value-key="id"
            multiple
            show-checkbox
            collapse-tags
            collapse-tags-tooltip
            :render-after-expand="false"
            :filter-node-method="filterNodeMethod"
            filterable
            clearable
            style="width: 180px"
            placeholder="请选择所在地点位置"
          />
        </el-form-item>
        
        <el-form-item label="设备状态" class="form-item-wrapper">
          <el-select
            v-model="queryForm.equipStatus"
            placeholder="全部"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value === null ? 'all' : item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备类型" class="form-item-wrapper">
          <el-select
            v-model="queryForm.equipType"
            placeholder="全部"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in equipTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备名称" class="form-item-wrapper">
          <el-input
            v-model="queryForm.equipName"
            placeholder="请输入设备名称"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item class="action-buttons">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" :disabled="tableData.list.length === 0" @click="handleExportAll" style="margin-left: 8px;">
            全部导出
          </el-button>
          <el-button type="success" :disabled="selectedRows.length === 0" @click="handleExportSelected" style="margin-left: 8px;">
            导出选中
          </el-button>
          <span style="margin-left: 12px; color: #909399; font-size: 14px; line-height: 32px;">
            已选择 {{ selectedRows.length }} 条
          </span>
        </el-form-item>
      </el-form>

      <el-table
        :data="tableData.list"
        border
        highlight-current-row
        stripe
        row-key="id"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" header-align="center" width="40" />
        <el-table-column prop="equipName" label="设备名称" min-width="160" />
        <el-table-column prop="equipNum" label="设备编号" min-width="180" />
        <el-table-column label="设备类型" min-width="120">
          <template #default="{ row }">
            {{ getEquipTypeLabel(row.equipType) }}
          </template>
        </el-table-column>
        <el-table-column label="设备状态" width="80">
          <template #default="{ row }">
            <el-tag size="small" :type="getStatusTagType(row)">
              {{ getStatusLabel(row) }}
            </el-tag>
          </template>
        </el-table-column>
         <el-table-column label="所属商户" min-width="160">
          <template #default="{ row }">
            {{ row.tenantName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="所在地点位置" min-width="180">
          <template #default="{ row }">
            {{ row.location || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="table-footer">
        <Pagination :pageProps="pageProps" layout="prev, pager, next" @search="getList" />
      </div>
    </div>

    <!-- 设备详情抽屉 -->
    <EquipmentListDialog ref="equipmentListDialogRef" @listChange="handleListChange" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import Pagination from '@/components/Pagination/Index.vue'
import { equipStatusList, equipDetail, getEquipStatus } from '@/api/collect'
import { getMerchantByName, getLocationTree } from '@/api/settle'
import type { LocationTreeNode } from '@/api/types/location'
import EquipmentListDialog from './components/EquipmentListDialog.vue'
import { exportFile } from '@/api/export'

type EquipmentStatus = 0 | 1 | 2 // 0-离线，1-在线，2-故障

const loading = ref(false)
const tableData = reactive({
  list: [] as any[],
})

const pageProps = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})

const equipmentStatus = reactive({
  totalCount: 0,
  onlineCount: 0,
  offlineCount: 0,
  faultCount: 0,
})

const queryForm = reactive({
  tenantId: null as number | null,
  locationIds: [] as number[],
  equipStatus: null as EquipmentStatus | null,
  equipType: null as number | null,
  equipName: '' as string,
})

const merchantList = ref<any[]>([])
const fullLocationTree = ref<LocationTreeNode[]>([])
const equipmentListDialogRef = ref<InstanceType<typeof EquipmentListDialog>>()
const selectedRows = ref<any[]>([])
const locationTreeProps = {
  label: 'name',
  children: 'children',
}

const statusOptions = [
  { label: '全部', value: null },
  { label: '离线', value: 0 },
  { label: '在线', value: 1 },
  { label: '故障', value: 2 },
]

const equipTypeOptions = [
  { label: '电表', value: 1 },
  { label: '水表', value: 2 },
  { label: '气表', value: 3 },
  { label: '智慧用电监控终端', value: 4 },
  { label: '网关', value: 5 },
]

const statusCardList = [
  { label: '总数', key: 'totalCount', type: 'normal' },
  { label: '在线', key: 'onlineCount', type: 'success' },
  { label: '离线', key: 'offlineCount', type: 'warning' },
  { label: '故障', key: 'faultCount', type: 'danger' },
]

const statusLabelMap: Record<number, string> = {
  0: '离线',
  1: '在线',
  2: '故障',
}

const searchMerchant = (name: string) => {
  getMerchantList(name)
}

const getMerchantList = (name?: string) => {
  getMerchantByName(name)
    .then((res: any) => {
      if (res.success && Array.isArray(res.data)) {
        merchantList.value = res.data
      } else {
        merchantList.value = []
      }
    })
    .catch((err: any) => {
      console.error('获取商户列表失败', err)
    })
}

const handleMerchantChange = () => {
  queryForm.locationIds = []
  if (!queryForm.tenantId) {
    fullLocationTree.value = []
    return
  }
  loadLocationTree()
}

const loadLocationTree = async () => {
  if (!queryForm.tenantId) return
  try {
    const res = await getLocationTree(queryForm.tenantId)
    if (res.success && Array.isArray(res.data)) {
      fullLocationTree.value = res.data
    } else {
      fullLocationTree.value = []
    }
  } catch (error) {
    console.error('加载地点位置失败', error)
    ElMessage.error('地点位置获取失败')
    fullLocationTree.value = []
  }
}

const filterNodeMethod = (value: string, data: any) => {
  if (!value) return true
  return data.name?.includes(value)
}

const handleSearch = () => {
  pageProps.pageNum = 1
  getList()
}

const handleReset = () => {
  Object.assign(queryForm, {
    tenantId: null,
    locationIds: [],
    equipStatus: null,
    equipType: null,
    equipName: '',
  })
  Object.assign(pageProps, {
    pageNum: 1,
    pageSize: 10,
    total: 0,
  })
  fullLocationTree.value = []
  getList()
}

const handleListChange = () => {
  setTimeout(() => {
    loadEquipmentStatus() 
    getList()
  }, 200)
}

const getList = () => {
  loading.value = true
  equipStatusList({
    pageNum: pageProps.pageNum,
    pageSize: pageProps.pageSize,
    tenantId: queryForm.tenantId || undefined,
    locationIds: queryForm.locationIds,
    equipStatus: queryForm.equipStatus !== null ? queryForm.equipStatus : undefined,
    equipType: queryForm.equipType || undefined,
    equipName: queryForm.equipName || undefined,
  })
    .then((res: any) => {
      const records = res?.data?.records || []
      tableData.list = records
      pageProps.total = res?.data?.total || 0
    })
    .catch((err: any) => {
      console.error('获取设备列表失败', err)
      tableData.list = []
      pageProps.total = 0
      ElMessage.error(err?.msg || '获取设备列表失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 获取设备状态数量
const loadEquipmentStatus = () => {
  getEquipStatus()
    .then((res: any) => {
      if (res.success && res.data) {
        equipmentStatus.totalCount = res.data.totalCount || 0
        equipmentStatus.onlineCount = res.data.onlineCount || 0
        equipmentStatus.offlineCount = res.data.offlineCount || 0
        equipmentStatus.faultCount = res.data.faultCount || 0
      }
    })
    .catch((err: any) => {
      console.error('获取设备状态数量失败', err)
      // 失败时重置为0
      equipmentStatus.totalCount = 0
      equipmentStatus.onlineCount = 0
      equipmentStatus.offlineCount = 0
      equipmentStatus.faultCount = 0
    })
}

const resolveStatusCode = (row: any): EquipmentStatus | null => {
  const status = row?.equipStatus
  if (typeof status === 'number' && (status === 0 || status === 1 || status === 2)) {
    return status as EquipmentStatus
  }
  return null
}

const getStatusLabel = (row: any) => {
  const code = resolveStatusCode(row)
  return code !== null ? statusLabelMap[code] : '未知'
}

const getStatusTagType = (row: any) => {
  const code = resolveStatusCode(row)
  if (code === 1) return 'success' // 在线
  if (code === 0) return 'warning' // 离线
  if (code === 2) return 'danger' // 故障
  return 'info'
}

const getEquipTypeLabel = (type: number | null | undefined) => {
  if (type === null || type === undefined) return '-'
  const option = equipTypeOptions.find(item => item.value === type)
  return option ? option.label : '-'
}

const handleView = (row: any) => {
  if (!equipmentListDialogRef.value) return
  
  equipmentListDialogRef.value.dialogVisible = true
  equipmentListDialogRef.value.dialogStatus = 'view'
  equipmentListDialogRef.value.isDisabled = false
  
  nextTick(() => {
    equipDetail(row.id)
      .then((res: any) => {
        if (res.success && res.data) {
          const dialog = equipmentListDialogRef.value!
          const data = res.data
          
          Object.assign(dialog.formItem, data)
          
          // 处理数字类型字段
          if (data.equipStatus != null) {
            dialog.formItem.equipStatus = Number(data.equipStatus)
          }
          if (data.locationId != null) {
            dialog.formItem.locationId = Number(data.locationId)
          }
          
          // 处理设备图片
          dialog.formItem.uploadPhotoDtoList = data.equipPic 
            ? [{ url: data.equipPic, name: '设备图片' }]
            : []
          
          // 加载网关和模板列表
          if (data.orgId) {
            dialog.getNetList(data.orgId)
            dialog.getTempList(data.orgId)
          }
        }
      })
      .catch((err: any) => {
        console.error('获取设备详情失败', err)
        ElMessage.error(err?.msg || '获取设备详情失败')
      })
  })
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const handleExportAll = () => {
  if (tableData.list.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }
  exportFile('/acq-equip/export', '', queryForm)
    .then(() => {
      ElMessage.success('导出成功')
    })
    .catch((err: any) => {
      console.error('导出失败', err)
      ElMessage.error(err?.msg || '导出失败')
    })
}

const handleExportSelected = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  const idList = selectedRows.value.map((item: any) => item.id)
  exportFile('/acq-equip/export', '', { ids: idList })
    .then(() => {
      ElMessage.success('导出成功')
    })
    .catch((err: any) => {
      console.error('导出失败', err)
      ElMessage.error(err?.msg || '导出失败')
    })
}

onMounted(() => {
  getMerchantList()
  loadEquipmentStatus()
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - $headerHeight - 38px - 40px);
  padding: 16px;
}

.collect-equipment-status {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-form {
  margin-top: 4px;
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;

  :deep(.el-form-item) {
    margin-right: 20px;
    margin-bottom: 12px;
  }

  :deep(.el-form-item.action-buttons) {
    margin-left: 20px;
    margin-right: 0;
  }
}

.status-card-wrapper {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

:deep(.el-form-item) {
  margin-bottom: 12px !important;
}

:deep(.el-form-item:last-child) {
  margin-right: 0;
}

.table-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 16px;
}

.status-card {
  flex: 1;
  min-width: 160px;
  padding: 16px 20px;
  border: 1px solid #f9f9f9;
  border-radius: 8px;
  background: linear-gradient(145deg, #fff, #ffffff);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;

  .status-label {
    font-size: 18px;
    font-weight: 700;
    color: #606266;
  }

  .status-value {
    font-size: 28px;
    font-weight: 700;

    &.normal {
      color: #2ac48d;
    }

    &.success {
      color: #2ac48d;
    }

    &.warning {
      color: #faad14;
    }

    &.danger {
      color: #f56c6c;
    }
  }
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  font-size: 13px;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}
</style>
